const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config')
// 注册用户
exports.regUser = (req, res) => {
  const userInfo = req.body
  // if(!userInfo.username || !userInfo.password) {
  //   return res.send({status: 1, message: '用户名或密码不能为空'})
  // }
  const sql = 'select * from ev_users where username=?'
  db.query(sql, userInfo.username, (err, results) => {
    if(err) {
      return res.cc(err)
    }
    if(results.length > 0) {
      return res.cc('用户名被占用，请更换其他用户名')
    }
    // TODO, 注册新用户
    userInfo.password = bcrypt.hashSync(userInfo.password, 10) // 对用户的密码,进行 bcrype 加密，返回值是加密之后的密码字符串
    const sql = 'insert into ev_users set ?'
    db.query(sql, {username: userInfo.username, password: userInfo.password}, (err, results) => {
      if(err) {
        return res.cc(err)
      }
      if(results.affectedRows !== 1) {
        return res.cc('注册用户失败，请稍后再试')
      }
      res.cc('注册成功', 0)
    })
  })
}

// 登录
exports.loginUser = (req, res) => {
  const userInfo = req.body
  const sql = 'select * from ev_users where username=?'
  db.query(sql, userInfo.username, (err, results) => {
    // console.log(results)
    if(err) {
      return res.cc(err) // 查询失败
    }
    if(results.length !== 1) {
      return res.cc('登录失败') // 查询结果错误
    }
    // 判断密码是否正确
    const compareResult = bcrypt.compareSync(userInfo.password, results[0].password)
    if(!compareResult) {
      return res.cc('密码错误')
    }
    const user = {...results[0], password: '', user_pic: ''} // 剔除密码和头像
    const tokenStr = jwt.sign(user, config.jwtSecretKey, {expiresIn: config.expiresIn})
    // console.log(tokenStr)
    res.send({
      status: 0,
      message: '登录成功',
      token: 'Bearer ' + tokenStr
    })
  })
}